import 'package:flutter_first_project/constant/index.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Tokenmanager {
//定义变量
  String? _token = '';
  // 定义变量存储刷新token
  String? _refreshToken = '';
  // 初始化首选项
  Future<SharedPreferences> _getInstance() {
    return SharedPreferences.getInstance(); // 获取首选项实例
  }

  // 初始化token
  init() async {
    // 获取首选项实例
    final prefs = await _getInstance();
    // 获取token
    _token = prefs.getString(GlobalVariable.tokenKey) ?? '';
    // 获取刷新token  
    _refreshToken = prefs.getString(GlobalVariable.REFRESH_TOKEN_KEY) ?? '';
  }

  // 设置token
  setToken(String token,{String? refreshToken}) async {
    final prefs = await _getInstance(); //获取首选项实例
    prefs.setString(GlobalVariable.tokenKey, token); // 设置token
    _token = token; // 赋值
    if(refreshToken != null){
      prefs.setString(GlobalVariable.REFRESH_TOKEN_KEY, refreshToken);
      _refreshToken = refreshToken;
    }
  }

  // 获取token
  getToken() {
    return _token ?? '';
  }
  // 获取刷新token
  getRefreshToken() {
    return _refreshToken ?? '';
  }

  // 删除token
  deleteToken() async {
    final prefs = await _getInstance();
      _token = null; //清空token
        _refreshToken = null;
    prefs.remove(GlobalVariable.tokenKey);

    prefs.remove(GlobalVariable.REFRESH_TOKEN_KEY);
  
  }
}

final tokenManager = Tokenmanager();
